package biz.almas.uycnr.crawler.crawler.downloder;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.log4j.Logger;

import biz.almas.uycnr.crawler.constant.Constant;

public class UYCNRDownloader {

	// 定义日志输出对象
	public static Logger logger = Logger.getLogger(UYCNRDownloader.class);

	public static String download(String xmlUrl, String path, String fileName) throws IOException {
		
		logger.info("开始读取" + xmlUrl + "的数据");
		
		long beginTime = System.currentTimeMillis();
		// 1、获取并打开连接
		URL url = new URL(xmlUrl);
		HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
		httpURLConnection.setRequestMethod("GET");
		httpURLConnection.connect();

		// 2、读取并保存数据
		InputStream is = httpURLConnection.getInputStream();
		BufferedInputStream bis = new BufferedInputStream(is);
		File pathFile = new File(Constant.XML_SAVE_PATH + path);
		if (!pathFile.exists()) {
			if (!pathFile.mkdirs()) {
				throw new IOException("无法创建文件");
			}
		}
		
		String filePath = Constant.XML_SAVE_PATH + path + "/" + fileName + ".xml";
		
		FileOutputStream fos = new FileOutputStream(filePath);

		BufferedOutputStream bos = new BufferedOutputStream(fos);

		int word = 0;
		while ((word = bis.read()) != -1) {
			bos.write(word);
		}

		bos.close();
		fos.close();
		bis.close();
		is.close();
		
		long endTime = System.currentTimeMillis();

		logger.info("读取" + xmlUrl + "的数据结束，共花" + (endTime - beginTime) + "毫秒");
		
		return filePath;
	}
}
